package com.sxdz.pay

import com.fasterxml.jackson.databind.ObjectMapper
import com.sxdz.constant.GlobalConstant
import com.sxdz.pay.util.MD5
import com.sxdz.pay.util.SignUtils
import com.sxdz.pay.util.XmlUtils
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

/**
 * Created by lzw on 2016/8/16.
 * 移动支付订单查询接口
 */

@RestController
@CompileStatic
@TypeChecked
@RequestMapping("payQuery")
class   PayQueryApi {

    private final static String version = "2.0";
    private final static String charset = "UTF-8";
    private final static String sign_type = "MD5";

    public static Logger logger=LoggerFactory.getLogger(PayMentApi.getClass())

    /***
     * 订单查询结果
     * @param outTradeNo
     * @param transactionId
     * @return
     */
    @RequestMapping(value="queryOrder")
   public static String  queryInfo(String outTradeNo,String transactionId){

        SortedMap<String, String> map = new TreeMap<String,String>()//写入集合的数据是有序
        map.put("out_trade_no",outTradeNo)//商户订单号
        map.put("transaction_id",transactionId)//威富通订单号

        map.put("service", "trade.single.query");
        map.put("version", version);
        map.put("charset", charset);
        map.put("sign_type", sign_type);
        map.put("mch_id", GlobalConstant.getString("mch_id"));

        String key =  GlobalConstant.getString("key");
        String reqUrl =  GlobalConstant.getString("req_url");
        map.put("nonce_str", String.valueOf(new Date().getTime()));

        Map<String,String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() +1) * 10);
        SignUtils.buildPayParams(buf,params,false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + key, "utf-8");
        map.put("sign", sign);

        println("reqUrl:" + reqUrl);

        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;
        Map<String, String> resultMap = null;
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map),"utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);

            if(response != null && response.getEntity() != null){
                resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                res = XmlUtils.toXml(resultMap);
                logger.info("请求结果：" + res);

                if(!SignUtils.checkParam(resultMap, key)){
                    res = "验证签名不通过";
                }else{
                    if("0".equals(resultMap.get("status"))){
                        if("0".equals(resultMap.get("result_code"))){
                            logger.info("业务成功，在这里做相应的逻辑处理");
                            String trade_state = resultMap.get("trade_state");
                            logger.info("trade_state : " + trade_state);
                            logger.info("这里商户需要同步自己的订单状态。。。");
                        }else{
                            logger.info("业务失败，尝试重新请求，并查看错误代码描叙");
                        }
                    }else{
                        logger.info("这里是请求参数有问题...");
                    }
                }
            }else{
                res = "操作失败!";
            }
        } catch (Exception e) {
            e.printStackTrace()
            res = "操作失败";
        } finally {
            if(response != null){
                response.close();
            }
            if(client != null){
                client.close();
            }
        }
        Map<String,String> result = new HashMap<String,String>();
        if(res.startsWith("<")){
            result.put("status", "200");
            result.put("msg", "操作成功，请在日志文件中查看");
        }else{
            result.put("status", "500");
            result.put("msg", res);
        }
       ObjectMapper om=new ObjectMapper();
       String json=om.writeValueAsString(resultMap)
       logger.info("*********************查询支付接口返回**********************"+json);
       return json;
    }
    /**
     * 退款查询
     * @param outTradeNo
     * @param transactionId
     * @param outRefundNo
     * @param refundId
     * @return
     */
   // @RequestMapping(value="queryRefund")
   public static String queryRefund(String outTradeNo,String transactionId,String outRefundNo,String refundId){

        SortedMap<String, String> map = new TreeMap<String,String>()
        map.put("out_trade_no",outTradeNo)
        map.put("transaction_id",transactionId)
        map.put("out_refund_no",outRefundNo)
        map.put("refund_id",refundId)

        map.put("service", "trade.refund.query");
        map.put("version", version);
        map.put("charset", charset);
        map.put("sign_type", sign_type);

        String key = GlobalConstant.getString("key");
        String reqUrl = GlobalConstant.getString("req_url");
        map.put("mch_id", GlobalConstant.getString("mch_id"));
        map.put("nonce_str", String.valueOf(new Date().getTime()));

        Map<String,String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() +1) * 10);
        SignUtils.buildPayParams(buf,params,false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + key, "utf-8");
        map.put("sign", sign);

        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String res = null;
        Map<String,String> resultMap = null;
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map),"utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if(response != null && response.getEntity() != null){
                resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
                res = XmlUtils.toXml(resultMap);
                logger.info("请求退款结果结果：" + res);

                if(!SignUtils.checkParam(resultMap, key)){
                    res = "验证签名不通过";
                }
            }else{
                res = "操作失败!";
            }
        } catch (Exception e) {
            e.printStackTrace()
            res = "操作失败";
        } finally {
            if(response != null){
                response.close();
            }
            if(client != null){
                client.close();
            }
        }
        Map<String,String> result = new HashMap<String,String>();
        if(res.startsWith("<")){
            result.put("status", "200");
            result.put("msg", "操作成功，请在日志文件中查看");
        }else{
            result.put("status", "500");
            result.put("msg", res);
        }
       ObjectMapper om=new ObjectMapper();
       String json=om.writeValueAsString(resultMap)
       logger.info("*********************查询支付退款接口返回**********************"+json);

       return json;
    }
}
